package com.example.controller;

import com.example.pojo.Result;
import com.example.pojo.User;
import com.example.pojo.UserToken;
import com.example.service.impl.UserServiceImpl;
import com.example.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@Slf4j
@RestController
public class LoginController {

    @Autowired
    private UserServiceImpl userService;

    @PostMapping("/login")
    public Result login(@RequestBody User user){
        User user1=userService.login(user);
        if (user1!=null){
            Map<String,Object> map=new HashMap<>();
            map.put("id",user1.getId());
            map.put("nickname",user1.getNickname());
            map.put("passwords",user1.getPasswords());
            String jwt = JwtUtils.generateJwt(map);
            UserToken userToken=new UserToken();
            userToken.setToken(jwt);
            userToken.setUserType(user1.getUserType());

            return Result.success(userToken) ;
        }else {
            return Result.error("用户名或密码错误");
        }
    }
}
